package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>管理员用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramsMap) {


        //1.接受前端的用户名和密码
        String name = paramsMap.get("name");
        String password = paramsMap.get("password");


        //2.判断是否为空
        if (StringUtils.isEmpty(name)|| StringUtils.isEmpty(password)){

            throw new LeadNewsException("你都用户名或密码为空");
        }

        //3.判断数据的用户名字密码收获和数据库的一样
        AdUser adUser = query().eq( "name",name).one();


        if (null == adUser){
            // 查不到数据则报错
            throw  new LeadNewsException("用户名或者密码错误");
        }

        //4.密码校验
        //4.1密码加盐后进行md5
        password += adUser.getSalt();

        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //4.2判断密码是否正确，这里数据库里面的密码是加盐后的，所以外面输入的密码也需要加盐才能进行判断
        if (!adUser.getPassword().equals(encryptedPwd)){
            throw new LeadNewsException("用户名或者密码错误");
        }

        //5.密码通过了生成令牌token 返回给前端浏览器，确认通过
        //5.1生成令牌
        String token = AppJwtUtil.createToken(adUser.getId().longValue());

        //5.2封装结构，返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUser);

        return map;
    }

    public static void main(String[] args) {
        String pwd = "admin";
        String salt = "123abc";
        System.out.println("用户信息===="+DigestUtils.md5DigestAsHex((pwd+salt).getBytes()));
    }
}
